package com.ywb.interceptor;

import com.ywb.utils.CurrentHolder;
import com.ywb.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String requestUrI = request.getRequestURI();
//        if (requestUrI.contains("login"))
//        {
//            log.info("登录请求");
//            return true;
//        }
        String token = request.getHeader("token");
        if (token==null||token.isEmpty())
        {
            log.info("token不存在");
            response.setStatus(401);
            return false;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("当前用户id为："+empId);
        } catch (Exception e) {
            log.info("token解析失败");
            response.setStatus(401);
            return false;
        }
        log.info("token解析成功");
        return true;

    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        CurrentHolder.remove();
        log.info("线程池中变量删除");
    }

}
